package service

import (
	"gitee.com/dayu1985/can_api/service/base"
	"gitee.com/dayu1985/can_api/models/sqlbean"
	"time"
	"gitee.com/dayu1985/framework/logging"
	"gitee.com/dayu1985/can_api/errors"
	"gitee.com/dayu1985/framework/storage/file"
)

// 读取系统应用
var applicationView *sqlbean.App

func (this *SysService) GetApp() *sqlbean.App {
	if applicationView != nil {
		return applicationView
	}
	applicationView = new(sqlbean.App)
	_, err := this.E.Table(applicationView).Get(applicationView)
	if err != nil {
		logging.Error("查询异常", err.Error())
	}
	return applicationView
}

type menu struct {
	ID          string `json:"_id" xorm:"varchar(50) pk '_id'"`
	Name        string `json:"name" xorm:"name"`               //功能名称
	Icon        string `json:"icon" xorm:"icon"`               //功能图标
	Type        string `json:"type" xorm:"type"`               //功能类型
	Value       string `json:"value" xorm:"value"`             //功能地址
	Parent      string `json:"-",xorm:"parent"`                //父功能
	Orientation string `json:"orientation" xorm:"orientation"` //屏幕方向
	Order       int    `json:"order" xorm:"order"`             //排序
	Remark      string `json:"remark" xorm:"remark"`           //备注
	Children    []menu `json:"children,omitempty"`             //子目录
}

func (this *SysService) GetMenus(ty, parent string) (interface{}, error) {
	menus := make([]menu, 0)
	sess := this.E.Table(sqlbean.AppMenu{}).Alias("ms").Where("ms.status = ?", 1)
	if ty != "" {
		sess.And("mm.type = ?", ty)
	}
	err := sess.Find(&menus)
	if err != nil {
		return nil, errors.XormSearchErr(err.Error())
	}
	if parent == "" {
		parent = "0"
	}
	return this.analyzeMenus(menus, parent), nil
}

func (this *SysService) GetMenusWidthNoChildren(ids ... string) (interface{}, error) {
	menus := make([]menu, 0)
	err := this.E.Table(sqlbean.AppMenu{}).Alias("ms").Where("ms.status = ?", 1).In("_id", ids).Find(&menus)
	if err != nil {
		return nil, errors.XormSearchErr(err.Error())
	}
	return menus, nil
}

func (this *SysService) BannerList(ty string) (interface{}, error) {
	sess := this.E.Table(sqlbean.AppBanner{}).Where("status = 1 and position = ? and begin < ? and end > ?", ty, time.Now().Unix(), time.Now().Unix()).
		OrderBy("order asc,changed desc")
	if ty == "index" {
		ads := make([]struct {
			Image  *string `json:"image" xorm:"image"`   //图片资源
			Href   *string `json:"href" xorm:"href"`     //目标链接
			Remark *string `json:"remark" xorm:"remark"` //备注
		}, 0)
		err := sess.Find(&ads)
		if err != nil {
			return nil, errors.XormSearchErr(err.Error())
		}
		return ads, nil
	} else {
		ad := new(struct {
			Image    *string `json:"image" xorm:"image"`       //图片资源
			Href     *string `json:"href" xorm:"href"`         //目标链接
			Duration *string `json:"duration" xorm:"duration"` //显示时长（秒）
			Remark   *string `json:"remark" xorm:"remark"`     //备注
		})
		_, err := sess.Get(ad)
		if err != nil {
			return nil, errors.XormSearchErr(err.Error())
		}
		return ad, nil
	}
}

func (this *SysService) AppVersion(ty string) (*sqlbean.AppVersion, error) {
	v := sqlbean.AppVersion{}
	_, err := this.E.Table(v).Where("platform = ?", ty).OrderBy("version desc").Get(&v)
	return &v, err
}

func (this *SysService) analyzeMenus(menus []menu, pid string) []menu {
	l := make([]menu, 0)
	for _, m := range menus {
		if pid == m.Parent {
			m.Children = this.analyzeMenus(menus, m.ID)
			l = append(l, m)
		}

	}
	return l
}

type SysService struct {
	E    *base.Service
	File file.Uploader
}

func NewSysService() *SysService {
	u := new(SysService)
	//uploader, err := file.NewUploader(app.GetConfig())
	//u.File = uploader
	//if err != nil {
	//	panic(err)
	//}
	//
	base.RegisterService(u)
	return u
}

func init() {
	base.AfterInitOracleFn(func() {
		//sess := base.Serve
		//oldapp := new(sqlbean.App)
		//sess.Table(oldapp).Get(oldapp)
		//now := time.Now().Unix()
		//if oldapp.ID == nil {
		//	id := bson.NewObjectId().Hex()
		//	app := sqlbean.App{
		//
		//		Code:    "0",
		//		Name:    "深水APP",
		//		Logo:    "https://cdn-1.wp.nginx.com/wp-content/themes/nginx-theme/assets/img/logo.png",
		//		Brief:   "新版APP",
		//		Version: "1.0.0",
		//		Bean:    sqlbean.Bean{ID: &id, Created: &now, Changed: &now,},
		//	}
		//	_, err := sess.Insert(app)
		//	if err != nil {
		//		logging.Error("插入数据异常", err)
		//	}
		//
		//} else {
		//	_, err := sess.ID(oldapp.ID).Update(oldapp)
		//	if err != nil {
		//		logging.Error("更新数据异常", err)
		//	}
		//}
	})
}
